import Vue from 'vue';
import { Component } from 'vue-property-decorator';
import {fetchapi} from 'services/api/fetchapi';
import {ObsSettings} from 'components/shared/ReactComponentList';
import GenericFormGroups from 'components/obs/inputs/GenericFormGroups.vue';
import { Inject } from 'services/core/injector';
import {MessageBox,Message,Loading  } from 'element-ui'
import mitt from 'mitt';
import { WindowsService } from 'services/windows';
import { ISettingsSubCategory, SettingsService } from 'services/settings/index';

Vue.use(Loading.directive);

Vue.prototype.$loading = Loading.service;


import { app,ipcRenderer } from 'electron';
import until from 'services/api/until';
@Component({
	components: {
		ObsSettings,
		GenericFormGroups
	},
})



export default class Main extends Vue {
    
	isLogin=false;
	changeStudioDialog=false;
	studioList:any[]=[];
	chooseStudioId:number=0;
	chooseStudioUserId:number=0;
	userInfo:any={};
	showSetting=false;

	fetchApi=new fetchapi();
	nowItem:any={};
	
	app_id:string="";
	internalCategoryName: string = null;
	@Inject() settingsService: SettingsService;
	@Inject() windowsService: WindowsService;

	
	
	created() {

	}

	mounted() {
		this.app_id=localStorage.getItem("app_id");
		this.getActivityList();
		this.getLoginStudioInfo();
		this.getStudioList();
		this.getUserInfo();
		this.getSalt();
		ipcRenderer.on("end_live",e=>{
			this.endLiveToActivity();
		})

		
	}

	getInitialCategoryName() {
		if (this.windowsService.state.child.queryParams) {
		  return this.windowsService.state.child.queryParams.categoryName || 'General';
		}
		return 'General';
	}

	getAllData(){
		return this.settingsService.state;
	}

	settingsData(categoryName:string) {
		
		console.log(this.settingsService.state)
		return this.settingsService.state[categoryName]?.formData ?? [];
	}
	
	save(settingsData: ISettingsSubCategory[],categoryName:string) {

		this.settingsService.setSettings(categoryName, settingsData);
	}


	
	get categoryName() {
		if (this.internalCategoryName == null) {
		  this.internalCategoryName = this.getInitialCategoryName();
		}
	
		return this.internalCategoryName;
	}

	
    activity_list:any[]=[];
	//获取活动列表
	async getActivityList(){
		let app_id=this.app_id;
		let list_type="doing"
		let page=1
		let each_page=10
		let classes_id=""
		let name=""
		let srcUrl="/teaching_studio_api/activity/newest?app_id="+app_id+"&list_type="+list_type+"&page="+page+"&each_page="+each_page+"&classes_id="+classes_id+"&name="+name
		const data:any=await this.fetchApi.fetchGet(srcUrl)
        if(data.errcode==0){
            this.activity_list=data.other.list;
			this.$forceUpdate();
        }
		console.log(data)
	}
	studioInfo:any={};
	//获取登录的工作室
	async getLoginStudioInfo(){
		let app_id=this.app_id;
		let srcUrl="/teaching_studio_api/studio/login_studio?app_id="+app_id
		const data:any=await this.fetchApi.fetchGet(srcUrl)
		if(data.errcode==0){
			this.getStudioInfo(data.other)
		}
	}
	//获取登录的用户信息
	async getUserInfo(){
		let app_id=this.app_id;
		let srcUrl="/teaching_studio_api/member/login_user?app_id="+app_id
		const data:any=await this.fetchApi.fetchGet(srcUrl)
		if(data.errcode==0){
			this.userInfo=data.other;
			this.chooseStudioUserId=data.other.user_id;
			
		}
	}


	//获取登录的工作室
	async getStudioInfo(id:number){
		let app_id=this.app_id;
		let srcUrl="/api_nologin/studio_open/info?app_id="+app_id+"&id="+id;
		const data:any=await this.fetchApi.fetchGet(srcUrl)
		if(data.errcode==0){
			this.chooseStudioId=id
			this.studioInfo=data.other
		}
	}
	//更换工作室信息
	async chooseStudio(id:number,user_id:number){
		this.chooseStudioId = id
        this.chooseStudioUserId = user_id
	}
	 // 获取该公众号下的工作室列表
	 async getStudioList() {
		let app_id=this.app_id;
		let srcUrl="/teaching_studio_api/studio/wechat/studio?app_id="+app_id
		const data:any=await this.fetchApi.fetchGet(srcUrl)
		if (data.errcode == 0) {
			this.studioList = data.other
			
		}
	}

	//确认切换工作室
	async surechangeStudio() {
		let app_id = this.app_id;
		let to_studio_id = this.chooseStudioId
		let to_user_id = this.chooseStudioUserId
		let token_reback=1;
		let srcUrl="/teaching_studio_api/studio/to/studio?app_id="+app_id+"&to_studio_id="+to_studio_id+"&to_user_id="+to_user_id+"&token_reback="+token_reback
		const data:any=await this.fetchApi.fetchGet(srcUrl)
		if (data.errcode == 0) {
			this.changeStudioDialog = false
			localStorage.setItem("jwt_token",data.other)
			this.getActivityList();
			this.getStudioInfo(to_studio_id);

		}
	}
	//显示切换工作室
	toShowChange(){
		this.changeStudioDialog=true;
	}

	//获取时间
	getTime(time:number){
		return until.formatDate(time*1000);
	}

	//开始直播
	async beginLive(item:any){
		let app_id = this.app_id;
		let activity_id = item.activity_id
		let srcUrl="/teaching_studio_api/activity_live/is_live?app_id="+app_id+"&activity_id="+activity_id

		const data:any=await this.fetchApi.fetchGet(srcUrl);
		
		if (data.errcode == 0) {
			
		
			if (data.other.is_live) {
				// ipcRenderer.send("foo",{url:data.other.rtmp_push});

				// this.setData(data.other.rtmp_push)

				// setTimeout(()=>{
				// 	this.$emit("begin_live",data.other.rtmp_push)
				// },1000)
				
			
				MessageBox.confirm('当前已有直播在进行，是否确认关闭当前直播创建新的直播?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.nowItem=item
					this.endLive(item)
				}).catch(() => {
	
				});

			}
			else{
				this.nowItem=item
				this.createLive(item)
			}
			
		   
		}
	}
	//结束直播并返回活动
	async endLiveToActivity(){
		let app_id = this.app_id;
		let computer_code = "123456"
	
		let salt = this.salt;
		let activity_id = this.nowItem.activity_id
		let srcUrl="/teaching_studio_api/activity_live/end"
		const data:any = await this.fetchApi.fetchPost(srcUrl,{app_id,computer_code,salt,activity_id})
		if (data.errcode == 0) {
			Message.success("结束成功")
			this.getActivityList();
			setTimeout(()=>{
				this.$emit("end_live")
			},1000)

		}
	}



	//结束直播
	async endLive(item:any){
		let app_id = this.app_id;
		let computer_code = "123456"
	
		let salt = this.salt;
		let activity_id = item.activity_id
		let srcUrl="/teaching_studio_api/activity_live/end"
		const data:any = await this.fetchApi.fetchPost(srcUrl,{app_id,computer_code,salt,activity_id})
		if (data.errcode == 0) {
			Message.success("结束成功")
			this.getSalt();
			setTimeout(()=>{
				this.createLive(item)
			},1000)

		}
		else {

		}
	}
	salt="";
	//获取salt
	async getSalt(){
		let app_id=this.app_id;
		let computer_code="123456"
		let srcUrl="/tool/form_salt/?app_id="+app_id+"&computer_code="+computer_code
		const data:any=await this.fetchApi.fetchGet(srcUrl);
		if(data.errcode==0){
			this.salt=data.other;
		}
	}
	loginOut(){
		localStorage.setItem("jwt_token","");
		this.$emit("loginOut")
	}

	async setData(pushUrl:string){
		let allData=this.getAllData();
		console.log(allData)
		for(let res in allData){
			if(res=='General'){
				let jsonData=allData[res];
				jsonData.formData.map(json=>{
					json.parameters.map(itemjson=>{
						if(itemjson.name=='RecordWhenStreaming'){
							itemjson.value=true
							itemjson.currentValue=true
						}
						
						
					})
				})
				this.save(jsonData.formData,res)
			}
			if(res=='Stream'){
				let jsonData=allData[res];
				jsonData.formData.map(json=>{
					json.parameters.map(itemjson=>{
						if(itemjson.name=='streamType'){
							itemjson.value="rtmp_custom"
							itemjson.currentValue="rtmp_custom"
						}
						if(itemjson.name=='server'){
							itemjson.value=pushUrl
							itemjson.currentValue=pushUrl	
							
						}
						if(itemjson.name=='key'){
							itemjson.value=""
							itemjson.currentValue=""	
							
						}
						
					})
				})
				this.save(jsonData.formData,res)
			}
			if(res=='Output'){
				let jsonData=allData[res];
				jsonData.formData.map(json=>{
					json.parameters.map(itemjson=>{
						if(itemjson.name=='Mode'){
							itemjson.value="Simple"
							itemjson.currentValue="Simple"
				
						}
						if(itemjson.name=='VBitrate'){
							itemjson.value=2500
							itemjson.currentValue=2500
						
						}
						if(itemjson.name=='StreamEncoder'){
							itemjson.value='qsv'
							itemjson.currentValue='qsv'
						
						}
						
					})
				})
				this.save(jsonData.formData,res)
			}
			if(res=='Video'){
				let jsonData=allData[res];

				console.log(res)
				jsonData.formData.map(json=>{
					json.parameters.map(itemjson=>{
						if(itemjson.name=='Base'){
							itemjson.value="1920x1080"
							itemjson.currentValue="1920x1080"
				
						}
						if(itemjson.name=='Output'){
							itemjson.value="960x540"
							itemjson.currentValue="960x540"
						
						}
						if(itemjson.name=='ScaleType'){
							itemjson.value='bilinear'
							itemjson.currentValue='bilinear'
					
						}
						if(itemjson.name=='FPSType'){
							itemjson.value='Integer FPS Value'
							itemjson.currentValue='Integer FPS Value';
						}
						if(itemjson.name=='FPSInt'){
			
							itemjson.value=20
							itemjson.currentValue=20
						
						}
						
						
					})
				})
				this.save(jsonData.formData,res)
			}
		}

	}

	//创建新的直播流
	async createLive(item:any){
		let app_id = this.app_id;
		let computer_code ="123456";
	
		let salt=this.salt
		let activity_id = item.activity_id
		let live_type = "rtmp"
		let srcUrl="/teaching_studio_api/activity_live/begin"
		const data:any=await this.fetchApi.fetchPost(srcUrl,{app_id,computer_code,activity_id,live_type,salt})
	
		if (data.errcode == 0) {
			this.getSalt();
			// ipcRenderer.send("foo",{url:data.other.PushUrl});


			this.setData(data.other.PushUrl)


			setTimeout(()=>{
				this.$emit("begin_live",data.other.PushUrl)
			},1000)
			

		}
		else {

		}
	}
}
